package com.apotik.legenda.dao;

import java.math.BigDecimal;
import java.util.List;

import javax.swing.JOptionPane;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Projections;

import com.apotik.legenda.model.SalesTrx;
import com.apotik.legenda.util.HibernateUtil;

public class SalesTrxDao extends CommonDao<SalesTrx> {

	public SalesTrxDao() {
		super(SalesTrx.class);
		
		SessionFactory sf = HibernateUtil.getSessionFactory();
		setSessionFactory(sf);
	}
	
	/*public boolean saveOrUpdate(SalesTrx obj){
		boolean isSucces = false;
		
		try {
			Session session = HibernateUtil.getSessionFactory().openSession();
			session.beginTransaction();
			session.saveOrUpdate(obj);
			session.getTransaction().commit();
			session.close();
			isSucces = true;
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
		}

		return isSucces;
	}*/
	
	
	@SuppressWarnings("unchecked")
	public BigDecimal sum(String propertyName, Criterion...criterions){
		BigDecimal result = BigDecimal.ZERO;
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			Criteria cr = session.createCriteria(SalesTrx.class);
			if (criterions!=null) {
				for(Criterion crit : criterions) {
					cr.add(crit);
				}
			}
			cr.setProjection(Projections.sum(propertyName));
			List<BigDecimal> list = cr.list();
			
			if(list.size()>0){
				result = list.get(0);
			}
			
		}catch (Exception e) {
			JOptionPane.showMessageDialog(null, e.getMessage(), "Exception", JOptionPane.ERROR_MESSAGE);
		} finally {
			session.close();
		}
		
		return result;
	}
	
}
